package com.glela.order.service.impl.order.amqp;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glela.activ.service.domain.OActivAvlProductVo;
import com.glela.activ.service.domain.avl.OActivAvlGiftProductVo;
import com.glela.biz.RedPacketBiz;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.GoodsSelfTypeEnum;
import com.glela.common.constant.GoodsTypeEnum;
import com.glela.common.constant.OpenStoreTypeEnum;
import com.glela.common.constant.OrderStatusEnum;
import com.glela.common.constant.UserJournalStatusEnum;
import com.glela.common.exception.PlatformException;
import com.glela.common.util.Config;
import com.glela.common.util.DateUtil;
import com.glela.common.util.NumberUtil;
import com.glela.common.util.OrderUtil;
import com.glela.company.model.CompanyXz;
import com.glela.domain.dto.ConsumeRedPacketRequest;
import com.glela.goods.model.Inventory;
import com.glela.goods.model.LimitTimeSaleDetail;
import com.glela.goods.model.vo.InventoryVo;
import com.glela.goods.model.vo.StoreVo;
import com.glela.goods.service.LimitTimeSaleDetailService;
import com.glela.live.mapper.LiveOrderMapper;
import com.glela.live.model.LiveOrder;
import com.glela.order.model.Commision;
import com.glela.order.model.OrderDetail;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderSettlement;
import com.glela.order.model.request.RequestOrderDetail;
import com.glela.order.model.response.RespAddOrderInfo;
import com.glela.order.model.response.order.RespOrderGiftsProductVo;
import com.glela.order.model.response.order.RespPromotionVo;
import com.glela.order.model.vo.order.ErrorMsgGoods;
import com.glela.order.model.vo.order.UserRedPacketVo;
import com.glela.order.model.vo.order.UserWalletVo;
import com.glela.order.service.impl.AbstractOrderServiceImpl;
import com.glela.order.service.impl.order.OrderServiceImpl5;
import com.glela.order.service.impl.vo.OrderActivInfoVo;
import com.glela.order.service.impl.vo.OrderAddParamsVo;
import com.glela.order.util.UserPromotionComparator;
import com.glela.packet.model.RedPacket;
import com.glela.packet.model.RedPacketOwner;
import com.glela.packet.service.RedPacketOwnerService;
import com.glela.packet.service.RedPacketService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CUserMoneyChange;
import com.glela.platform.model.CUserPointTransaction;
import com.glela.platform.model.MoneyBusinessType;
import com.glela.platform.model.User;
import com.glela.platform.model.UserAddress;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserPointJournal;
import com.glela.platform.model.UserPromotion;
import com.glela.platform.model.request.ReqHeaderVo;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.vo.GoodsSimpleVo;
import com.glela.platform.vo.UserPromotionVo;

@Service("orderAmqpService")
public class OrderAmqpServiceImpl extends AbstractOrderServiceImpl {
	private static Logger				logger	= LoggerFactory.getLogger(OrderServiceImpl5.class);
	@Autowired
	private LimitTimeSaleDetailService	limitTimeSaleDetailService;
	@Autowired
	private LiveOrderMapper				liveOrderMapper;
	@Autowired
	private RedPacketOwnerService		redPacketOwnerService;
	@Autowired
	private RedPacketService			redPacketService;
	@Autowired
	private RedPacketBiz				redPacketBiz;

	@Override
	public ResponseResultModel<RespAddOrderInfo> addOrderInfo(RequestOrderDetail reqOrderDetail) throws PlatformException {
		RespAddOrderInfo respAddOrderInfo = new RespAddOrderInfo();
		ResponseResultModel<RespAddOrderInfo> resultModel = new ResponseResultModel<RespAddOrderInfo>(ErrorEnum.C10000, respAddOrderInfo);
		ReqHeaderVo reqHeader = reqOrderDetail.getReqHeader();
		DateTime nowTime = new DateTime();//当前时间，以次时间为去结算开始时间点

		//兔币
		UserRedPacketVo reqRedPacket = reqOrderDetail.getRedPacket();
		//优惠券
		RespPromotionVo respPromotionVo = null;
		List<UserPromotionVo> selcetAvlProm = null;

		try {
			/** 防重复提交 */
			if (_check_double_submit(reqOrderDetail.getToken())) {
				resultModel.setError(ErrorEnum.C20001);
				warnLog(reqHeader, "用户[{}]重复提交token{}", reqOrderDetail.getUserId(), reqOrderDetail.getToken());
				return resultModel;
			}
			reqOrderDetail.setSubmitType(1);

			//		respAddOrderInfo.setToken(reqOrderDetail.getToken());

			String orderSn = reqOrderDetail.getParentOrderSn();
			if (StringUtils.isBlank(orderSn)) {
				//生成交易单号
				orderSn = getOrderObjectSn();
			}
			respAddOrderInfo.setOrderSn(orderSn);

			List<OrderDetail> _req_order_detail_list = reqOrderDetail.getOrderDetailList();
			respAddOrderInfo.getErrorMsg().getAvlGoods().addAll(_req_order_detail_list);

			//购买商品明细
			if (CollectionUtils.isEmpty(_req_order_detail_list)) {
				resultModel.setError(ErrorEnum.C20701);
				return resultModel;
			}

			// 对海外购商品进行认证
			ResponseResultModel<RespAddOrderInfo> TempModel = validationOverseasGoods(reqOrderDetail);
			if (TempModel != null) {// 有错误信息 返回
				return TempModel;
			}
			 
			//当前登录人信息
			Long _login_user_id = reqOrderDetail.getUserId();
			ResponseUser _login_user = userService.selectUserRoleById(_login_user_id);
			if (_login_user == null || _login_user.getUserId() == null) {
				resultModel.setError(ErrorEnum.C20111);
				errorLog(reqHeader, "下单人[{}]不存在", _login_user_id);
				return resultModel;
			}

			Long _talentId = _req_order_detail_list.get(0).getTalentId();
			//获取订单所在店铺
			ResponseUser _store_user = null;
			try {
				_store_user = getStoreUser(reqHeader, _login_user, _talentId);
			} catch (PlatformException e1) {
				resultModel.setError(e1.getErrorEnum());
				resultModel.setMessage(e1.getMessage());
				return resultModel;
			}

			//分佣信息
			//			String recommendFrom = _store_user.getRecommendFrom();//推荐人身份ID
			String recommendFrom = _store_user.getPersionId();//推荐人身份ID
			String talentTeacher = StringUtils.EMPTY;//达人导师/经纪人身份id

			//校验订单基本信息
			if (_check_avail_req_get_order_obj(_login_user, reqOrderDetail, resultModel)) {
				return resultModel;
			}

			//用户配送地址
			UserAddress userAddress = userAddressService.selectUserAddressById(_login_user_id, reqOrderDetail.getMemberDeliveryAddressId());
			if (userAddress == null) {
				resultModel.setError(ErrorEnum.C20129);
				return resultModel;
			}

			Map<Long, InventoryVo> _check_inventory_map = new HashMap<Long, InventoryVo>();
			createInventoryMap(_check_inventory_map, _req_order_detail_list);
			if (_check_inventory_map.size() != _req_order_detail_list.size()) {
				resultModel.setError(ErrorEnum.C40002);
				warnLog(reqHeader, "订单下单商品查询对应库存数量不符：{}-{}", JSON.toJSONString(_req_order_detail_list), JSON.toJSONString(_check_inventory_map));
				return resultModel;
			}

			long _xz_sister_user_id = BaseConstants.XZ_SISTER;
			int _diff_total_price = 0;//价格变动差价综合

			long _gain_xzb = 0;//获得妆币|有效商品
			OrderAddParamsVo orderVo = new OrderAddParamsVo(_login_user_id);
			String _now_time = nowTime.toString(DateUtil.DATE_FORMATTER);
			long nowTimeMillis = nowTime.getMillis();

			Set<Long> productIds = new HashSet<>();
			boolean isOpenStoreOrder = false;//是否是首单
			try {
				isOpenStoreOrder = isOpenOrderStore(reqOrderDetail, _check_inventory_map, _login_user, productIds);
			} catch (PlatformException e) {
				resultModel.setError(e.getErrorEnum());
				resultModel.setMessage(e.getMessage());
				return resultModel;
			}

			//批量查询分时抢购信息
			Map<Long, LimitTimeSaleDetail> _check_limit_sale_detail_map = limitTimeSaleDetailService.queryByProductIds(productIds, nowTime.toDate());
			long _store_user_id = _store_user.getUserId();//店主用户id
			List<OrderDetail> _avl_goods_list = new LinkedList<OrderDetail>();
			List<ErrorMsgGoods> _err_goods_list = new LinkedList<ErrorMsgGoods>();
			for (OrderDetail _req_order_detail : _req_order_detail_list) {
				if (_req_order_detail.getQuantity() == null || _req_order_detail.getQuantity().intValue() < 1) {
					_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "购买数量必须大于等于1"));
					continue;
				}

				//校验库存
				InventoryVo _check_inventory = _check_inventory_map.get(_req_order_detail.getInventoryId());
				if (_check_inventory == null || _check_inventory.getStatus() != 1 || _check_inventory.getInventoryNum() < _req_order_detail.getQuantity()) {
					_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "库存不足"));
					//				_check_inventory_map.remove(_req_order_detail.getInventoryId());
					continue;
				}
				if (_check_inventory.getId() != _req_order_detail.getInventoryId() || _check_inventory.getProductId() != _req_order_detail.getProductId() || _check_inventory.getGoodId() != _req_order_detail.getGoodId()) {
					_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "库存不足"));
					//				_check_inventory_map.remove(_req_order_detail.getInventoryId());
					continue;
				}
				_req_order_detail.setUserId(_login_user.getUserId());

				/*校验*/
				if (_check_share_goods_and_talent(_talentId, _req_order_detail.getTalentId(), _req_order_detail.getGoodId(), _req_order_detail.getTalentShareGoodId(), resultModel)) {
					//				_check_inventory_map.remove(_req_order_detail.getInventoryId());
					return resultModel;
				}

				long _check_product_inventory_num = 0;
				LimitTimeSaleDetail _check_limit_time_sale_detail = _check_limit_sale_detail_map.get(_check_inventory.getProductId());
				if (_check_limit_time_sale_detail == null) {//不是分时抢购取实际库存
					_check_product_inventory_num = _check_inventory.getInventoryNum();
				} else {//是分时抢购，去实际库存、秒杀库存和显示库存最小值
					if (_check_limit_time_sale_detail.getUserSkuCount().intValue() < _req_order_detail.getQuantity()) {//总限购数
						_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "超过限购数"));
						continue;
					}
					if (_check_inventory.getInventoryNum() <= _check_limit_time_sale_detail.getShowCount()) {
						_check_product_inventory_num = _check_inventory.getInventoryNum();
					} else {
						_check_product_inventory_num = _check_limit_time_sale_detail.getShowCount();
					}
					if (_check_product_inventory_num > _check_limit_time_sale_detail.getSkuCount()) {
						_check_product_inventory_num = _check_limit_time_sale_detail.getSkuCount();
					}
				}
				if (_req_order_detail.getQuantity() > _check_product_inventory_num) {//无库存
					_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "库存不足"));
					//				_check_inventory_map.remove(_req_order_detail.getInventoryId());
					continue;
				}

				//			_check_inventory.setApplywelfareId(0);
				//			_req_order_detail.setApplywelfareId(0);
				_req_order_detail.setActivityType(0);
				_req_order_detail.setIsOpenStoreGoods(_check_inventory.isOpenGoods() ? 1 : 0);

				//1：b、c区商品不能一同支付
				//			if (_check_inventory.getGoodsType() != GoodsTypeEnum.T1.getCode()) {
				//				_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "只能购买B区商品"));
				//				_check_inventory_map.remove(_req_order_detail.getInventoryId());
				//				continue;
				//			}
				//2：下单商品必须上架可售
				if (_check_inventory.isNotOnTheShelf(nowTimeMillis)) {
					_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, ErrorEnum.C20401.getMessage()));
					//				_check_inventory_map.remove(_req_order_detail.getInventoryId());
					continue;
				}

				int _check_sale_price = 0;

				//判断商品是否为分时抢购商品
				//			LimitTimeSaleDetail _check_limit_time_sale_detail = limitTimeSaleDetailService.queryByProductId(_check_inventory.getProductId(), nowTime.toDate());

				//判断库存、判断售价
				if (_check_limit_time_sale_detail == null) {
					if (_store_user_id == _xz_sister_user_id) {// 当前登录人的推荐人为： 校妆姐姐，所以取校妆姐姐价
						_check_sale_price = _check_inventory.getXzSalePrice();
					} else {// 当前登录人的推荐人为： 一般店主，所以取店主价
						_check_sale_price = _check_inventory.getSalePrice();
					}
				} else {
					_req_order_detail.setLimitTimeSaleId(_check_limit_time_sale_detail.getLimitTimeSaleId());
					_req_order_detail.setLimitTimeSaleDetailId(_check_limit_time_sale_detail.getId());
					_check_sale_price = _check_limit_time_sale_detail.getProductSalePrice();

					//校验用户限购数
					//查询已购数（包含待支付,待发货,待收货,已完成,交易成功,交易关闭）
					Integer limitSaleNums = this.orderDetailMapper.selectLimitSaleNums(_login_user.getUserId(), _check_limit_time_sale_detail.getLimitTimeSaleId(), _check_inventory.getProductId(), _check_inventory.getId());
					if (limitSaleNums != null && limitSaleNums + _req_order_detail.getQuantity() > _check_limit_time_sale_detail.getUserSkuCount()) {
						_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "超过每人限购数"));
						continue;
					}
				}

				if (_check_sale_price != _req_order_detail.getSalePrice()) {//价格不等
					int _diff_sale_price = _check_sale_price - _req_order_detail.getSalePrice();
					_diff_total_price += _diff_sale_price * _req_order_detail.getQuantity();
					_req_order_detail.setSalePriceDesc((_diff_sale_price < 0 ? "降价" : "涨价") + "￥" + NumberUtil.getFloatPrice(_diff_sale_price));
				}
				//			_req_order_detail.setSalePrice(_check_sale_price);
				_check_inventory.setSalePrice(_check_sale_price);

				//			if (_check_inventory.getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && _req_order_detail.getGoodsType() == GoodsTypeEnum.T1.getCode()) {//b区自营商品
				if (_req_order_detail.getSalePrice() <= 0 || _check_sale_price <= 0) {
					warnLog(reqHeader, "商品[{}-{}]销售价格小于等于0[{},{}] 请求报文：{}", _check_inventory.getGoodId(), _check_inventory.getProductId(), _check_sale_price, _req_order_detail.getSalePrice(), JSONObject.toJSONString(reqOrderDetail));
					_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "已下架"));
					//				_check_inventory_map.remove(_req_order_detail.getInventoryId());
					continue;
				}

				_req_order_detail.setBrandId(_check_inventory.getBrandId());
				_req_order_detail.setStoreId(_check_inventory.getStoreId());
				_req_order_detail.setSelfSupport(_check_inventory.getSelfSupport());
				_req_order_detail.setGoodsType(_check_inventory.getGoodsType());

				_avl_goods_list.add(_req_order_detail);

				orderVo.setValue(_check_sale_price, _check_inventory.getSettlementPrice(), _req_order_detail.getQuantity(), _check_inventory.getStoreId(), _check_inventory.getSelfSupport(), _check_inventory.getGoodId(), _check_inventory.getBrandId(), _req_order_detail, _check_inventory);

				if (_check_inventory.getScoreRate() > 0) {
					_gain_xzb += _check_inventory.getScoreRate() * _req_order_detail.getQuantity().intValue() * _check_inventory.getSalePrice();
				}
			}
			respAddOrderInfo.getErrorMsg().getInvalidGoods().clear();
			respAddOrderInfo.getErrorMsg().getInvalidGoods().addAll(_err_goods_list);

			respAddOrderInfo.getErrorMsg().getAvlGoods().clear();
			respAddOrderInfo.getErrorMsg().getAvlGoods().addAll(_avl_goods_list);

			respAddOrderInfo.setTotalProd(orderVo.getTotalQuantity());
			respAddOrderInfo.setAcquirableXzb(_gain_xzb);
			respAddOrderInfo.setTotalPrice(orderVo.getTotalPrice());

			//价格发生变动
			if (_diff_total_price != 0) {
				if (_diff_total_price < 0) {
					respAddOrderInfo.getErrorMsg().setDesPriceChanger("商品价格发生变动，累计降价￥" + NumberUtil.getFloatPrice(_diff_total_price));
				} else {
					respAddOrderInfo.getErrorMsg().setDesPriceChanger("商品价格发生变动，累计涨价￥" + NumberUtil.getFloatPrice(_diff_total_price));
				}
				//设置最新售价
				if (CollectionUtils.isNotEmpty(_avl_goods_list)) {
					for (OrderDetail orderDetail : _req_order_detail_list) {
						InventoryVo _check_inventory = _check_inventory_map.get(orderDetail.getInventoryId());
						orderDetail.setSalePrice(_check_inventory.getSalePrice());
					}
				}
				return resultModel;
			}

			//有失效商品，或者可用商品为空
			if (CollectionUtils.isNotEmpty(_err_goods_list) || CollectionUtils.isEmpty(_avl_goods_list)) {
				return resultModel;
			}

			UserPromotionVo userPromotion = null;
			/*满减满赠活动*/
			OrderActivInfoVo orderActivInfoVo = new OrderActivInfoVo();
			if (!isOpenStoreOrder) {
				_package_activ_order_detail(_avl_goods_list, orderActivInfoVo, _now_time);
				respAddOrderInfo.setDiscountFee(orderActivInfoVo.getDiscountFee());
				if (MapUtils.isNotEmpty(orderActivInfoVo.getGiftProducts())) {
					for (Long storeId : orderActivInfoVo.getGiftProducts().keySet()) {
						List<OActivAvlGiftProductVo> giftProducts = orderActivInfoVo.getGiftProducts().get(storeId);
						for (OActivAvlGiftProductVo oActivAvlGiftProductVo : giftProducts) {
							Inventory check_gift_inventory = inventoryMapper.selectByPrimaryKey(oActivAvlGiftProductVo.getInventoryId());
							if (check_gift_inventory != null) {
								oActivAvlGiftProductVo.setInventoryNum(check_gift_inventory.getInventoryNum());
							}
							RespOrderGiftsProductVo _add_resp_acitv_gift_product = _package_order_gift(oActivAvlGiftProductVo);
							if (oActivAvlGiftProductVo.getInventoryId() <= 0 || oActivAvlGiftProductVo.getInventoryNum() <= 0 || oActivAvlGiftProductVo.getInventoryNum() < oActivAvlGiftProductVo.getQuantity()) {
								//						reqOrderDetail.setSubmitType(1);
								_add_resp_acitv_gift_product.setMsg("赠品数量不足");
								respAddOrderInfo.getErrorMsg().getInvalidGifts().add(_add_resp_acitv_gift_product);
								continue;
							}
							respAddOrderInfo.getErrorMsg().getAvlGifts().getProducts().add(_add_resp_acitv_gift_product);
						}
					}
					if (reqOrderDetail.getSubmitType() != 1 && respAddOrderInfo.getErrorMsg().isHasInvalidGifts()) {
						return resultModel;
					}
				}

				/*优惠券*/
				if (reqOrderDetail.getPromotionId() > 0) {
					selcetAvlProm = selcetAvlProm(orderVo);
					for (UserPromotionVo userPromotionVo : selcetAvlProm) {
						if (userPromotion != null) {
							break;
						}
						if (userPromotionVo.getId() == reqOrderDetail.getPromotionId()) {
							userPromotion = userPromotionVo;
							break;
						}
					}
					if (userPromotion == null || userPromotion.getPromotionNumber() <= 0 || (userPromotion.getType() == 7 && (userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T0.getCode() && orderVo.isHasNoSelfGoods() && userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T1.getCode() && orderVo.isHasSelfGoods()))) {
						warnLog(reqHeader, "用户[{}]的优惠券[{}]不可用 {}", _login_user_id, reqOrderDetail.getPromotionId(), JSONObject.toJSONString(reqOrderDetail));
						resultModel.setError(ErrorEnum.C30110);
						return resultModel;
					}
					respPromotionVo = new RespPromotionVo();
					respPromotionVo.setUserPromotionId(reqOrderDetail.getPromotionId());
					respPromotionVo.setDiscountAmount(userPromotion.getDiscountAmount());
				}

				//兔币
				if (reqRedPacket != null) {
					RedPacketOwner checkRedPacketOwner = redPacketOwnerService.getRedPacketOwnerById(reqRedPacket.getOwnerId());
					if (checkRedPacketOwner == null) {
						warnLog(reqHeader, "用户[{}]的兔币[{}-{}]不存在", _login_user_id, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId());
						resultModel.setError(ErrorEnum.C20000);
						resultModel.setMessage("兔币无效");
						return resultModel;
					}
					if (checkRedPacketOwner.getId().intValue() != reqRedPacket.getOwnerId() || checkRedPacketOwner.getRedPacketId() != reqRedPacket.getRedPacketId() || checkRedPacketOwner.getOwnUserId() != _login_user_id.longValue()) {
						warnLog(reqHeader, "用户[{}]的兔币[{}-{}]不匹配实际兔币[{}-{}-{}]", _login_user_id, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId(), checkRedPacketOwner.getRedPacketId(), checkRedPacketOwner.getId(), checkRedPacketOwner.getOwnUserId());
						resultModel.setError(ErrorEnum.C20000);
						resultModel.setMessage("兔币“" + checkRedPacketOwner.getTitle() + "”未通过有效性校验，请联系客服处理");
						return resultModel;
					}

					if (checkRedPacketOwner.getRedPacketStatus() != 0) {
						warnLog(reqHeader, "用户[{}]的兔币[{}-{}]不可使用[{}]", _login_user_id, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId(), checkRedPacketOwner.getRedPacketStatus());
						resultModel.setError(ErrorEnum.C20000);
						switch (checkRedPacketOwner.getRedPacketStatus()) {
							case 1:
								resultModel.setMessage("兔币“" + checkRedPacketOwner.getTitle() + "”已被使用");
								break;
							case 2:
								resultModel.setMessage("兔币“" + checkRedPacketOwner.getTitle() + "”已过期");
								break;

							default:
								resultModel.setMessage("兔币“" + checkRedPacketOwner.getTitle() + "”不可用");
								break;
						}
						return resultModel;
					}
					if (checkRedPacketOwner.getEffectiveStartTime() == null || checkRedPacketOwner.getEffectiveStartTime().getTime() - nowTimeMillis > 0) {
						warnLog(reqHeader, "用户[{}]的兔币[{}-{}]不可使用[{}-{}]", _login_user_id, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId(), checkRedPacketOwner.getRedPacketStatus(), checkRedPacketOwner.getEffectiveStartTime());
						resultModel.setError(ErrorEnum.C20000);
						resultModel.setMessage("欲速则不达，兔币“" + checkRedPacketOwner.getTitle() + "”有效期还未到哦");
						return resultModel;
					}
					if (checkRedPacketOwner.getEffectiveEndTime() == null || checkRedPacketOwner.getEffectiveEndTime().getTime() - nowTimeMillis < 0) {
						warnLog(reqHeader, "用户[{}]的兔币[{}-{}]不可使用[{}-{}]", _login_user_id, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId(), checkRedPacketOwner.getRedPacketStatus(), checkRedPacketOwner.getEffectiveEndTime());
						resultModel.setError(ErrorEnum.C20000);
						resultModel.setMessage("时机已失，兔币“" + checkRedPacketOwner.getTitle() + "”已失效");
						return resultModel;
					}
					RedPacket checkRedPacket = redPacketService.getRedPacketById(checkRedPacketOwner.getRedPacketId());
					if (checkRedPacket == null || checkRedPacket.getStatus() != 0) {
						warnLog(reqHeader, "用户[{}]的兔币[{}-{}]不存在或已使用", _login_user_id, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId(), checkRedPacketOwner.getRedPacketStatus(), checkRedPacketOwner.getEffectiveStartTime());
						resultModel.setError(ErrorEnum.C20000);
						resultModel.setMessage("兔币“" + checkRedPacketOwner.getTitle() + "”已失效");
						return resultModel;
					}
					if (reqRedPacket.getAmount() > checkRedPacket.getAmount()) {
						warnLog(reqHeader, "用户[{}]的兔币[{}-{}]使用金额[{}]超过了实际最大金额[{}]", _login_user_id, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId(), reqRedPacket.getAmount(), checkRedPacket.getAmount());
						resultModel.setError(ErrorEnum.C20000);
						resultModel.setMessage("兔币“" + checkRedPacketOwner.getTitle() + "”使用金额超出范围");
						return resultModel;
					}
					reqRedPacket.setAmount(checkRedPacket.getAmount());
					respAddOrderInfo.setRedPacket(reqRedPacket);
				} else {
					reqRedPacket = null;
				}
			}

			/*生成交易单*/
			OrderObject addOrderObj = new OrderObject();
			addOrderObj.setOpenStore(isOpenStoreOrder ? 1 : 0);//累计开店及购买了开店商品，标记开店单

			addOrderObj.setOrderSn(orderSn);
			respAddOrderInfo.setOrderSn(addOrderObj.getOrderSn());

			//生产父单
			createOrderObj(addOrderObj, reqOrderDetail, userAddress);
			addOrderObj.setCreateTime(_now_time);
			addOrderObj.setUpdateTime(_now_time);
			addOrderObj.setUserId(_login_user_id);//当前购买人
			addOrderObj.setTotalPrice(orderVo.getTotalPrice());//设置总销售金额
			addOrderObj.setTotalFee(addOrderObj.getTotalPrice());//总支付金额

			//设置兔币金额
			if (reqRedPacket != null) {
				addOrderObj.setRedPacketId(reqRedPacket.getRedPacketId());
				addOrderObj.setRedPacketOwnerId(reqRedPacket.getOwnerId());
				addOrderObj.setRedPacketFee(reqRedPacket.getAmount());
			} else {
				addOrderObj.setRedPacketFee(0l);
			}
			//设置优惠券优惠金额
			if (userPromotion == null) {
				addOrderObj.setPromotionDiscount(0);
			} else {
				//				addOrderObj.setPromotionId(userPromotion.getPromotionId());
				addOrderObj.setPromotionDiscount((int) userPromotion.getDiscountAmount());
			}
			//运费
			//设置运费
			if (orderActivInfoVo.isFreeShipping()) {
				addOrderObj.setFreight(0);
			} else {
				BaseRestrictions freightRts = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.FULL_FREE_FREIGHT);
				if (freightRts != null && freightRts.getRestrictions() > addOrderObj.getTotalPrice().intValue()) {
					addOrderObj.setFreight(freightRts.getExperience());
				} else {
					addOrderObj.setFreight(_get_default_freight());
				}
			}
			//			运费不参与计算
			//活动抵扣
			if (orderActivInfoVo.getDiscountFee() > 0) {
				addOrderObj.setTotalFee((int) (addOrderObj.getTotalFee() - orderActivInfoVo.getDiscountFee()));
				if (addOrderObj.getTotalFee().intValue() < 0) {
					throw new PlatformException(ErrorEnum.C20002, "活动设置异常");
				}
				addOrderObj.setoActivDiscountFee(orderActivInfoVo.getDiscountFee());
			} else {
				addOrderObj.setoActivDiscountFee(0l);
			}

			//兔币不参与运费抵扣，单独计算
			if (addOrderObj.getRedPacketFee() > 0) {
				if (addOrderObj.getTotalFee() <= 0) {
					throw new PlatformException(ErrorEnum.C20000, "兔币使用过多");
				}
				addOrderObj.setTotalFee(addOrderObj.getTotalFee().intValue() - addOrderObj.getRedPacketFee().intValue());
				if (addOrderObj.getTotalFee().intValue() < 0) {
					addOrderObj.setRedPacketFee(addOrderObj.getRedPacketFee() + addOrderObj.getTotalFee());
					reqRedPacket.setAmount(addOrderObj.getRedPacketFee());
					addOrderObj.setTotalFee(0);
				}
				addOrderObj.setRedPacketOwnerId(reqRedPacket.getOwnerId());
			}

			//优惠不参与运费抵扣，单独计算
			if (addOrderObj.getPromotionDiscount().intValue() > 0) {//有优惠，减掉优惠等于实付现金
				addOrderObj.setTotalFee(addOrderObj.getTotalFee().intValue() - addOrderObj.getPromotionDiscount().intValue());
				//实付现金小于0，多抵扣的部分从优惠中扣除，实付现金设置为0
				if (addOrderObj.getTotalFee().intValue() < 0 && addOrderObj.getTotalFee().intValue() + addOrderObj.getPromotionDiscount() >= 0) {
					addOrderObj.setPromotionDiscount(addOrderObj.getPromotionDiscount().intValue() + addOrderObj.getTotalFee());
					userPromotion.setDiscountAmount(addOrderObj.getPromotionDiscount());
					addOrderObj.setTotalFee(0);
				}
				//			else if (addOrderObj.getTotalFee().intValue() == 0 && (addOrderObj.getCashCoin().intValue() > 0 || addOrderObj.getBalancePaid().intValue() > 0)) {
				//				throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getDesc());
				//			}
			}

			//			参与运费计算
			addOrderObj.setTotalFee(addOrderObj.getTotalFee() + addOrderObj.getFreight());
			//计算妆币余额抵扣应付，运费可以被妆币、余额抵扣
			addOrderObj.setTotalFee(addOrderObj.getTotalFee().intValue() - addOrderObj.getCashCoin() - addOrderObj.getBalancePaid());
			if (addOrderObj.getTotalFee().intValue() < 0) {//如果实付总金额小于0
				if (addOrderObj.getCashCoin().intValue() > 0 || addOrderObj.getBalancePaid().intValue() > 0) {//妆币或余额中有一个有大于0，提示用户余额或妆币食用过多
					throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getDesc());
				} else {//没有使用余额妆币，抛出异常，理论上不会走到这一步
					logger.error("订单下单实付金额为负：{}-{}", addOrderObj.getTotalFee(), JSONObject.toJSONString(reqOrderDetail));
					throw new PlatformException(ErrorEnum.C20000, "订单生成异常，请稍候再试");
				}
			}
			if (addOrderObj.getTotalFee().intValue() == 0) {//0元付订单直接待发货
				addOrderObj.setStatus(OrderStatusEnum.S2.getCode());
				respAddOrderInfo.setPaid(true);//已支付
				addOrderObj.setPayTime(_now_time);
				addOrderObj.setPayId(addOrderObj.getOrderSn());
				//			orderObject.setPayType(PayTypeEnum.T25.getCode());
			} else {
				addOrderObj.setStatus(OrderStatusEnum.S1.getCode());
			}
			// orderObject.setCommisionFee(commisionFee);
			//设置交易订单店中店用户id
			if (_avl_goods_list.get(0).getTalentId() > 0) {
				addOrderObj.setOpenStoreUserId(_avl_goods_list.get(0).getTalentId());
			} else {
				addOrderObj.setOpenStoreUserId(_store_user.getUserId());
			}

			/*事务回滚开始*/
			//		if (!orderTokenService.removeToken(reqOrderDetail.getToken())) {//防重复提交
			//			resultModel.setError(ErrorEnum.C20001);
			//			logger.error("用户:{}生成订单token重复:{}-{}", reqOrderDetail.getUserId(), reqOrderDetail.getToken(), JSON.toJSONString(reqOrderDetail));
			//			return resultModel;
			//		}

			//使用兔币
			if (addOrderObj.getRedPacketFee() > 0) {
				try {
					ConsumeRedPacketRequest consumeRedPacketRequest = new ConsumeRedPacketRequest();
					consumeRedPacketRequest.setRedPacketOwnerId(reqRedPacket.getOwnerId());
					consumeRedPacketRequest.setUserId(_login_user_id.intValue());
					consumeRedPacketRequest.setConsumeType(addOrderObj.getTotalFee().intValue() == 0 ? 1 : 0);
					if (!redPacketBiz.consumeRedPacket(consumeRedPacketRequest)) {
						errorLog(reqHeader, "用户[{}]的兔币[{}-{}]不可用", _login_user, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId());
						throw new PlatformException(ErrorEnum.C30110, "兔币不可用");
					}
					consumeRedPacketRequest = null;
				} catch (Exception e) {
					errorLog(reqHeader, "用户[{}]的兔币[{}-{}]不可用", _login_user, reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId());
					throw new PlatformException(ErrorEnum.C30110, "兔币不可用");
				}
			}

			//使用优惠券
			if (reqOrderDetail.getPromotionId() > 0) {
				if (!userPromotionService.modifyToUse(reqOrderDetail.getPromotionId())) {
					errorLog(reqHeader, "用户[{}]的优惠券[{}]不可用", _login_user, reqOrderDetail.getPromotionId());
					throw new PlatformException(ErrorEnum.C30110, "优惠券不可用");
				}
			}

			// 保存订单前 校验海外购信息
			ResponseResultModel<RespAddOrderInfo> TempModel1 = validationOverseasGoods(addOrderObj, reqOrderDetail,respAddOrderInfo);
			if (TempModel1 != null) {// 有错误信息 返回
				return TempModel1;
			}
			
			//生成交易订单
			int ooResult = orderDao.insertOrderObjectSelective(addOrderObj);
			if (ooResult != 1) {
				throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
			}
			//生成子单
			Map<Long, OrderInfo> orderInfoIdMap = new HashMap<Long, OrderInfo>();//以订单主键为索引的订单信息集合
			//		addOrderObj.getTotalFee();
			boolean isZeroOrder = addOrderObj.getTotalFee() == 0;//是否是0元单

			/*剩余金额*/
			long _total_surplus_discount_amount = addOrderObj.getPromotionDiscount();//剩余总优惠金额
			long _total_surplus_red_packet_fee = addOrderObj.getRedPacketFee();//剩余总兔币金额
			long _total_surplus_activ_discount_fee = addOrderObj.getoActivDiscountFee();//剩余总活动抵扣金额
			long _total_surplus_xzb = addOrderObj.getCashCoin();//剩余总妆币
			long _total_surplus_ye = addOrderObj.getBalancePaid();//剩余总余额
			int _total_surplus_freight = addOrderObj.getFreight();//剩余总运费

			//云飞分摊妆币、余额
			long _total_surplus_freigth_xzb = 0;//剩余总云飞分摊妆币额
			long _total_surplus_freigth_ye = 0;//剩余云飞分摊余额额

			/*妆币、余额抵扣运费，扣除运费占用妆币、余额
			 * 扣除逻辑；1.先抵扣余额，再抵扣妆币*/
			if (addOrderObj.getFreight().intValue() > addOrderObj.getTotalFee() && (_total_surplus_xzb > 0 || _total_surplus_ye > 0)) {
				long _temp_total_freight = addOrderObj.getFreight().intValue() - addOrderObj.getTotalFee();
				if (_temp_total_freight <= _total_surplus_ye) {//余额抵扣运费
					_total_surplus_freigth_ye = _temp_total_freight;
					_total_surplus_ye -= _temp_total_freight;
				} else {
					_total_surplus_freigth_ye = _total_surplus_ye;
					_temp_total_freight -= _total_surplus_ye;
					_total_surplus_ye = 0;

					_total_surplus_freigth_xzb = _temp_total_freight;
					_total_surplus_xzb -= _temp_total_freight;
				}
			}
			//实际拆分妆币、余额
			long _dive_total_ye = _total_surplus_ye;
			long _dive_total_xzb = _total_surplus_xzb;

			long _dive_total_freigth_xzb = _total_surplus_freigth_xzb;
			long _dive_total_freigth_ye = _total_surplus_freigth_ye;

			//循环分组的商品明细、先生成自订单明细再生成自订单
			int k = 0;
			int i = k = orderVo.getStoreOrderDetails().size();//总自订单数：用于控制子订单运费精度
			for (int storeId : orderVo.getStoreOrderDetails().keySet()) {
				i--;

				StoreVo storeVo = brandService.getStoreById(storeId);
				OrderInfo addOrderInfo = new OrderInfo();
				addOrderInfo.setTotalFee(0);
				createOrderInfo(addOrderInfo, reqOrderDetail, storeVo, userAddress);
				addOrderInfo.setOrderObjectId(addOrderObj.getId());
				addOrderInfo.setStatus(addOrderObj.getStatus());
				addOrderInfo.setUserId(_login_user_id);
				addOrderInfo.setCreateTime(_now_time);
				addOrderInfo.setUpdateTime(_now_time);
				addOrderInfo.setTotalPrice((int) orderVo.getStoreTotalAmount(storeId));
				addOrderInfo.setPayTime(addOrderObj.getPayTime());
				addOrderInfo.setPayId(addOrderObj.getPayId());

				double _order_info_rate = addOrderInfo.getTotalPrice().doubleValue() / addOrderObj.getTotalPrice();//子订单占总商品金额比例
				if (_total_surplus_freight > 0) {//有运费
					if (i == 0) {//最后一单，将剩余运费分到这一单
						addOrderInfo.setFreight(_total_surplus_freight);
					} else {//不是最后一个子订单，按精度四舍五入
						addOrderInfo.setFreight((int) Math.round(addOrderObj.getFreight() * _order_info_rate));
					}
					_total_surplus_freight -= addOrderInfo.getFreight();//计算剩余运费
				} else {
					addOrderInfo.setFreight(0);
				}
				//分摊妆币分摊云飞部分
				if (_total_surplus_freigth_xzb > 0) {
					if (i == 0) {
						addOrderInfo.setCashCoin((int) _total_surplus_freigth_xzb);
					} else {
						addOrderInfo.setCashCoin((int) Math.round(_dive_total_freigth_xzb * _order_info_rate));
					}
					_total_surplus_freigth_xzb -= addOrderInfo.getCashCoin();
				}
				//分摊余额分摊云飞部分
				if (_total_surplus_freigth_ye > 0) {
					if (i == 0) {
						addOrderInfo.setBalancePaid((int) _total_surplus_freigth_ye);
					} else {
						addOrderInfo.setBalancePaid((int) Math.round(_dive_total_freigth_ye * _order_info_rate));
					}
					_total_surplus_freigth_ye -= addOrderInfo.getBalancePaid();
				}

				List<OrderDetail> storeOrderDetails = orderVo.getStoreOrderDetails(storeId);
				int j = storeOrderDetails.size();
				for (OrderDetail orderDetail : storeOrderDetails) {
					j--;

					orderDetail.setCreateTime(_now_time);
					orderDetail.setUpdateTime(_now_time);
					orderDetail.setStatus(addOrderObj.getStatus());
					orderDetail.setRecommendFrom(recommendFrom);//普通推荐人身份id
					orderDetail.setMemberRecommend(_login_user.getMemberRecommend());//会员推荐人
					orderDetail.setTalentTeacher(talentTeacher);//达人导师/经纪人身份id
					orderDetail.setTotalPrice(orderDetail.getSalePrice().intValue() * orderDetail.getQuantity());
					//获取活动商品信息
					OActivAvlProductVo oActivAvlProductVo = orderActivInfoVo.getActivProducts().get(orderDetail.getProductId());
					if (oActivAvlProductVo != null) {
						orderDetail.setoActivId(oActivAvlProductVo.getActivId());
						orderDetail.setoActivDiscountFee(oActivAvlProductVo.getDiscontFee());
						_total_surplus_activ_discount_fee -= orderDetail.getoActivDiscountFee();
					} else {
						orderDetail.setoActivDiscountFee(0l);
					}

					double _order_detail_rate = orderDetail.getTotalPrice().doubleValue() / addOrderObj.getTotalPrice();//商品行销售总价占整单销售总价比例
					//计算优惠，需要考虑优惠类型，品牌、商品、通用
					long _order_detail_discount_amount = 0;
					if (_total_surplus_discount_amount > 0) {
						if (i == 0 && j == 0) {//最后一个子订单，将剩余优惠分到次单上
							_order_detail_discount_amount = _total_surplus_discount_amount;
						} else {//不是最后一单，按优惠券类型分摊到行
							_order_detail_discount_amount = compODPomotionDiscount(userPromotion, orderDetail, orderVo);
						}
						_total_surplus_discount_amount -= _order_detail_discount_amount;//计算剩余优惠金额
					}
					//计算兔币分摊
					long _order_detail_red_packet_fee = 0;
					if (_total_surplus_red_packet_fee > 0) {
						if (i == 0 && j == 0) {//最后一个子订单，将剩余兔币分到此单上
							_order_detail_red_packet_fee = _total_surplus_red_packet_fee;
						} else {//不是最后一单，按比例分摊到行
							_order_detail_red_packet_fee = Math.round(orderDetail.getTotalPrice().doubleValue() / orderVo.getTotalPricePromotion() * addOrderObj.getRedPacketFee());
						}
						_total_surplus_red_packet_fee -= _order_detail_red_packet_fee;//计算剩余优惠金额
					}
					//分摊妆币
					long _order_detail_xzb = 0;
					if (_total_surplus_xzb > 0) {
						if (i == 0 && j == 0) {//最后一单且最后一行时，剩余妆币分到最后一行
							_order_detail_xzb = _total_surplus_xzb;
						} else {//按比例分摊妆币
							_order_detail_xzb = Math.round(_dive_total_xzb * _order_detail_rate);
							if (_order_detail_xzb < 0) {//如果妆币为负数，赋值为0
								_order_detail_xzb = 0;
							}
						}
						_total_surplus_xzb -= _order_detail_xzb;//计算剩余可分妆币
					}
					//余额
					long _order_detail_ye = 0;
					if (_total_surplus_ye > 0) {
						if (i == 0 && j == 0) {//最后一单且最后一行时，剩余余额分到最后一行
							_order_detail_ye = _total_surplus_ye;
						} else {//按比例分摊余额
							_order_detail_ye = Math.round(_dive_total_ye * _order_detail_rate);
							if (_order_detail_ye < 0) {//余额为负数，赋值为0
								_order_detail_ye = 0;
							}
						}
						_total_surplus_ye -= _order_detail_ye;//计算剩余可分余额
					}
					//应付金额
					long _order_detail_total_fee = orderDetail.getTotalPrice().intValue() - orderDetail.getoActivDiscountFee() - _order_detail_discount_amount - _order_detail_red_packet_fee - _order_detail_xzb - _order_detail_ye;
					if (_order_detail_total_fee < 0) {//实付现金为负数
						if (_order_detail_xzb + _order_detail_ye + _order_detail_total_fee >= 0) {//当前分摊的妆币、余额总计>=当前实付现金（可抵扣）
							if (_order_detail_xzb + _order_detail_total_fee >= 0) {//精度分摊到妆币
								_order_detail_xzb += _order_detail_total_fee;
								_total_surplus_xzb -= _order_detail_total_fee;
							} else if (_order_detail_ye + _order_detail_total_fee >= 0) {//精度分摊到余额
								_order_detail_ye += _order_detail_total_fee;
								_total_surplus_ye -= _order_detail_total_fee;
							} else {//妆币、余额都小于负数，谁小就全额抵扣，剩余部分由大的补齐
								if (_order_detail_xzb > _order_detail_ye) {//妆币大于余额，实际分摊余额调整为0，剩余部分由妆币扣除
									_total_surplus_ye += _order_detail_ye;
									_order_detail_xzb += _order_detail_ye + _order_detail_total_fee;
									_total_surplus_xzb -= _order_detail_ye + _order_detail_total_fee;
									_order_detail_ye = 0;
								} else {//余额大于妆币，实际分摊妆币调整为0，剩余部分由余额扣除
									_total_surplus_xzb += _order_detail_xzb;
									_order_detail_ye += _order_detail_xzb + _order_detail_total_fee;
									_total_surplus_ye -= _order_detail_xzb + _order_detail_total_fee;
									_order_detail_xzb = 0;
								}
							}
							_order_detail_total_fee = 0;
						} else if (_order_detail_red_packet_fee + _order_detail_total_fee >= 0) {
							_order_detail_red_packet_fee += _order_detail_total_fee;
							_total_surplus_red_packet_fee -= _order_detail_total_fee;
							_order_detail_total_fee = 0;
						} else {//商品妆币和余额总计不扣抵扣负数，抛出异常
							logger.error("{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
							throw new PlatformException(ErrorEnum.C20000, "商品实付金额小于0");
						}
					}
					//0元付订单行应付现金不为0，调整妆币、余额使用量
					if (isZeroOrder && _order_detail_total_fee != 0) {
						if ((k > 1 && i > 0 || i == 0) && j > 0) {//不是最后一个子订单或子订单数为1并且不是最后一行
							if (_total_surplus_xzb + _total_surplus_ye > _order_detail_total_fee) {//能够从剩余妆币余额中扣减
								if (_total_surplus_xzb > _order_detail_total_fee && _total_surplus_ye > _order_detail_total_fee) {
									//剩余的可扣的妆币余额都大于多出的实付金额
									//妆币、余额两方均摊多出的实付金额
									long round = Math.round(_order_detail_total_fee / 2d);
									long afte = _order_detail_total_fee - round;
									if (_total_surplus_xzb > _total_surplus_ye) {//剩余妆币大于剩余余额，将分摊的大的从妆币扣除，小的从余额扣除
										if (round > afte) {
											_order_detail_xzb += round;
											_order_detail_ye += afte;
											_total_surplus_xzb -= round;
											_total_surplus_ye -= afte;
										} else {
											_order_detail_xzb += afte;
											_order_detail_ye += round;
											_total_surplus_xzb -= afte;
											_total_surplus_ye -= round;
										}
									} else {//剩余余额大于妆币，将分摊的大的从余额扣除，小的从妆币扣除
										if (round > afte) {
											_order_detail_xzb += afte;
											_order_detail_ye += round;
											_total_surplus_xzb -= afte;
											_total_surplus_ye -= round;
										} else {
											_order_detail_xzb += round;
											_order_detail_ye += afte;
											_total_surplus_xzb -= round;
											_total_surplus_ye -= afte;
										}
									}
								} else {
									if (_total_surplus_ye > _total_surplus_xzb) {//剩余余额大于剩余的妆币，妆币全部扣除，剩余多余支付的从余额扣除
										_order_detail_xzb += _total_surplus_xzb;
										_order_detail_ye += _order_detail_total_fee - _total_surplus_xzb;
										_total_surplus_ye -= _order_detail_total_fee - _total_surplus_xzb;
										_total_surplus_xzb = 0;
									} else {//剩余妆币大于剩余余额，余额全部扣除，剩余多于支付的从妆币扣除
										_order_detail_ye += _total_surplus_ye;
										_order_detail_xzb += _order_detail_total_fee - _total_surplus_ye;
										_total_surplus_xzb -= _order_detail_total_fee - _total_surplus_ye;
										_total_surplus_ye = 0;
									}
								}
								_order_detail_total_fee = 0;
							} else if (_order_detail_red_packet_fee >= _order_detail_total_fee) {
								_order_detail_red_packet_fee -= _order_detail_total_fee;
								_total_surplus_red_packet_fee += _order_detail_total_fee;
								_order_detail_total_fee = 0;
							} else {
								logger.error("{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
								throw new PlatformException(ErrorEnum.C20000, "0元付商品实付金额不等于0");
							}
						} else {//0元付订单最后一单，最后一行商品实付现金不为0
							logger.error("0元付订单最后一单，最后一行商品实付现金不为0:{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
							throw new PlatformException(ErrorEnum.C20000, "0元付商品实付金额不等于0");
						}
					}

					if (_order_detail_total_fee < 0) {
						logger.error("{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
						throw new PlatformException(ErrorEnum.C20000, "商品实付金额异常");
					}
					orderDetail.setCashCoin((int) _order_detail_xzb);
					orderDetail.setBalancePaid((int) _order_detail_ye);
					orderDetail.setPromotionDiscount((int) _order_detail_discount_amount);
					orderDetail.setRedPacketFee(_order_detail_red_packet_fee);
					if (orderDetail.getRedPacketFee() > 0) {
						orderDetail.setRedPacketId(addOrderObj.getRedPacketId());
					}
					orderDetail.setTotalFee((int) _order_detail_total_fee);

					addOrderInfo.setCashCoin(addOrderInfo.getCashCoin().intValue() + orderDetail.getCashCoin());
					addOrderInfo.setBalancePaid(addOrderInfo.getBalancePaid().intValue() + orderDetail.getBalancePaid());
					addOrderInfo.setPromotionDiscount(addOrderInfo.getPromotionDiscount().intValue() + orderDetail.getPromotionDiscount());
					addOrderInfo.setRedPacketFee(addOrderInfo.getRedPacketFee() + orderDetail.getRedPacketFee());
					addOrderInfo.setoActivDiscountFee(addOrderInfo.getoActivDiscountFee() + orderDetail.getoActivDiscountFee());
				}

				if (addOrderInfo.getPromotionDiscount() > 0) {
					addOrderInfo.setPromotionId(addOrderObj.getPromotionId());
				}
				if (addOrderInfo.getRedPacketFee() > 0) {
					addOrderInfo.setRedPacketId(addOrderObj.getRedPacketId());
				}
				//计算子单应付现金
				addOrderInfo.setTotalFee((int) (addOrderInfo.getTotalPrice() + addOrderInfo.getFreight().intValue() - addOrderInfo.getoActivDiscountFee() - addOrderInfo.getPromotionDiscount() - addOrderInfo.getRedPacketFee() - addOrderInfo.getCashCoin() - addOrderInfo.getBalancePaid()));
				if (addOrderInfo.getTotalFee() < 0) {
					logger.error("拆单后子单应付小于0:{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(addOrderInfo), addOrderInfo.getTotalFee());
					throw new PlatformException(ErrorEnum.C20000, "下单异常，请稍后再试");
				}

				orderDao.insertOrderInfoSelective(addOrderInfo);
				orderInfoIdMap.put(addOrderInfo.getId(), addOrderInfo);
				//封装赠品
				List<OrderDetail> _package_gift_order_detail = _package_gift_order_detail(storeId, reqOrderDetail.getSubmitType(), orderActivInfoVo);
				if (CollectionUtils.isNotEmpty(_package_gift_order_detail)) {
					storeOrderDetails.addAll(_package_gift_order_detail);
					createInventoryMap(_check_inventory_map, _package_gift_order_detail);
				}

				int liveCount = 0;
				for (OrderDetail orderDetail : storeOrderDetails) {
					orderDetail.setOrderId(addOrderInfo.getId());
					orderDetail.setOrderObjectId(addOrderObj.getId());
					orderDetail.setStatus(addOrderObj.getStatus());
					orderDetail.setUserId(_login_user_id);
					orderDetail.setTalentId(0l);//talentId置空
					//扣减库存
					_subInventory(_login_user, orderDetail);
					if (StringUtils.isNotBlank(orderDetail.getLivePlanId())) {
						liveCount++;
					}
				}
				orderDao.batchInsertOrderDetail(storeOrderDetails);
				if (liveCount > 0) {
					List<LiveOrder> liveOrderList = new ArrayList<>();
					/*String chatMessageText = _login_user.getNickName();
					Set<Integer> pids = new HashSet<>();*/
					for (OrderDetail orderDetail : storeOrderDetails) {
						if (StringUtils.isNotBlank(orderDetail.getLivePlanId())) {
							LiveOrder liveOrder = new LiveOrder();
							liveOrder.setLivePlanId(Integer.valueOf(orderDetail.getLivePlanId()));
							//							pids.add(liveOrder.getLivePlanId());
							liveOrder.setOrderDetailId(orderDetail.getId());
							liveOrder.setOrderInfoId(orderDetail.getOrderId());
							liveOrder.setOrderObjectId(orderDetail.getOrderObjectId());
							liveOrderList.add(liveOrder);
						}
					}
					if (!liveOrderList.isEmpty()) {
						liveOrderMapper.batchInsert(liveOrderList);
						/*for (Integer pid : pids) {
							chatRoomService.sendOrderMessage(pid,chatMessageText);
						}*/
					}
				}
			}

			if (_total_surplus_activ_discount_fee != 0) {
				logger.error("计算分摊活动抵扣金额异常：{}", JSON.toJSONString(orderActivInfoVo));
				throw new PlatformException(ErrorEnum.C21212, "活动优惠计算异常");
			}
			if (_total_surplus_red_packet_fee != 0) {
				warnLog(reqHeader, "计算分摊兔币抵扣金额未分摊完[{}-{}-{}]", reqRedPacket.getRedPacketId(), reqRedPacket.getOwnerId(), _total_surplus_red_packet_fee);
				throw new PlatformException(ErrorEnum.C21212, "兔币计算异常");
			}
			if (_total_surplus_discount_amount != 0 || _total_surplus_xzb != 0 || _total_surplus_ye != 0) {
				logger.error("下单时妆币、余额或优惠券使用过多：{}-{}-{}:{}", _total_surplus_xzb, _total_surplus_ye, _total_surplus_discount_amount, JSONObject.toJSONString(reqOrderDetail));
				throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getMessage());
			}
			if (_total_surplus_freight != 0) {
				logger.error("下单时运费分摊未完成：{}-{}", _total_surplus_freight, JSONObject.toJSONString(reqOrderDetail));
				throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getMessage());
			}
			//剩余赠品单独拆分订单
			if (MapUtils.isNotEmpty(orderActivInfoVo.getGiftProducts())) {
				for (Long storeId : orderActivInfoVo.getGiftProducts().keySet()) {
					StoreVo storeVo = brandService.getStoreById(storeId);
					//生成金额为0的子订单
					OrderInfo addOrderInfo = new OrderInfo();
					addOrderInfo.setOrderObjectId(addOrderObj.getId());
					addOrderInfo.setStatus(addOrderObj.getStatus());
					addOrderInfo.setUserId(_login_user_id);
					createOrderInfo(addOrderInfo, reqOrderDetail, storeVo, userAddress);

					//封装赠品明细
					List<OrderDetail> storeOrderDetails = _package_gift_order_detail(storeId, reqOrderDetail.getSubmitType(), orderActivInfoVo);
					if (CollectionUtils.isNotEmpty(storeOrderDetails)) {
						orderDao.insertOrderInfoSelective(addOrderInfo);
						orderInfoIdMap.put(addOrderInfo.getId(), addOrderInfo);

						for (OrderDetail orderDetail : storeOrderDetails) {
							orderDetail.setOrderId(addOrderInfo.getId());
							orderDetail.setOrderObjectId(addOrderObj.getId());
							orderDetail.setStatus(addOrderObj.getStatus());
							orderDetail.setUserId(_login_user_id);
							//扣减库存
							_subInventory(_login_user, orderDetail);
						}
						//保存商品明细
						orderDao.batchInsertOrderDetail(storeOrderDetails);
						createInventoryMap(_check_inventory_map, storeOrderDetails);
					}
				}
			}

			//================================================================================/
			if (addOrderObj.getCashCoin() > 0 || addOrderObj.getBalancePaid() > 0) {
				UserWalletVo _log_user_money = respAddOrderInfo.getUserMoney();
				List<CUserMoneyChange> _add_user_money_change_list = new LinkedList<>();
				if (addOrderObj.getCashCoin() > 0) {//记录现金币使用流水
					//扣除用户本次现金币
					if (respAddOrderInfo.isPaid()) {
						//直接扣减可用
						if (!userMoneyService.updateSubNormalAmount(_log_user_money.getXzb().getId(), _login_user_id, reqOrderDetail.getCashCoin())) {
							throw new PlatformException(ErrorEnum.C20125, "妆币不足");
						}
					} else {//扣减可用，增加冻结
						if (!userMoneyService.updateFreezeAmount(_log_user_money.getXzb().getId(), _login_user_id, reqOrderDetail.getCashCoin())) {
							throw new PlatformException(ErrorEnum.C20125, "妆币不足");
						}
					}
					MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(14);
					if (moneyBusinessType != null) {
						//记录事务
						CUserPointTransaction addCUserPointTransaction = new CUserPointTransaction();
						addCUserPointTransaction.setUserId(_login_user_id);
						addCUserPointTransaction.setOrderSn(StringUtils.EMPTY);
						addCUserPointTransaction.setOrderDetailId(0l);
						addCUserPointTransaction.setOrderObjectId(addOrderObj.getId());
						addCUserPointTransaction.setBusinessSourceId(addOrderObj.getId());

						addCUserPointTransaction.setBusinessTypeId(moneyBusinessType.getTypeId());
						addCUserPointTransaction.setBusinessTypeName(moneyBusinessType.getTypeName());
						addCUserPointTransaction.setAmount(-addOrderObj.getCashCoin().longValue());
						addCUserPointTransaction.setIsCustom(0);//是否手工处理单据
						addCUserPointTransaction.setIsDelete(0);//是否删除 0 未删除 1已删除
						addCUserPointTransaction.setTransactionStatus(respAddOrderInfo.isPaid() ? 1 : -1);//已处理
						addCUserPointTransaction.setCreateTime(nowTime.toDate());
						addCUserPointTransaction.setBusinessTime(nowTime.toDate());
						addCUserPointTransaction.setCreatorId(_login_user_id);
						addCUserPointTransaction.setCreatorName(_login_user.getNickName());
						//保存
						cUserPointTransactionService.insertSelective(addCUserPointTransaction);

						// 记录用户资产的变化
						CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
						_add_user_money_change_list.add(addCUserMoneyChange);

						addCUserMoneyChange.setCreatorId(_login_user_id);
						addCUserMoneyChange.setUserId(_login_user_id);
						addCUserMoneyChange.setOrderSn(addOrderObj.getId());// 源ID
						addCUserMoneyChange.setExtend1(addOrderObj.getOrderSn());
						addCUserMoneyChange.setChangeTime(nowTime.toDate());

						addCUserMoneyChange.setChangeAmount(addCUserPointTransaction.getAmount().intValue());
						addCUserMoneyChange.setNormalBeforAmount(_log_user_money.getXzb().getAvailQuantity());
						addCUserMoneyChange.setFreeBeforAmount(_log_user_money.getXzb().getFrozenQuantity());
						addCUserMoneyChange.setSourceType(Byte.valueOf("2"));// 积分
						if (respAddOrderInfo.isPaid()) {//已支付
							addCUserMoneyChange.setChangeFreeAmount(0);
							//插入流水
							UserPointJournal addUserPointJournal = new UserPointJournal();
							addUserPointJournal.setCreateTime(nowTime.toDate());
							addUserPointJournal.setOrderSn(StringUtils.EMPTY);
							addUserPointJournal.setOrderDetailId(0l);
							addUserPointJournal.setBusinessSourceId(addCUserPointTransaction.getId());//业务源单ID
							addUserPointJournal.setUserId(_login_user_id);//发生用户ID

							addUserPointJournal.setBusinessTypeId(moneyBusinessType.getTypeId());//业务类型ID
							addUserPointJournal.setBusinessTypeName(moneyBusinessType.getTypeName());//业务类型名称
							addUserPointJournal.setAmount(-addOrderObj.getCashCoin().longValue());//发生金额 允许负数
							addUserPointJournal.setIsCustom(0);//是否手工处理单据
							addUserPointJournal.setIsDelete(0);//是否删除 0 未删除 1已删除
							addUserPointJournal.setKeepAccountsType(moneyBusinessType.getKeepAccountsType());// 财务记账类型
							addUserPointJournal.setCreatorId(_login_user_id);
							addUserPointJournal.setCreatorName(_login_user.getNickName());
							userPointJournalService.addSelective(addUserPointJournal);
						} else {//未支付
							addCUserMoneyChange.setChangeFreeAmount(addOrderObj.getCashCoin());
						}
					}
				}
				if (addOrderObj.getBalancePaid() > 0) {
					//扣除余额
					if (respAddOrderInfo.isPaid()) {
						//直接扣除可用
						if (!userMoneyService.updateSubNormalAmount(_log_user_money.getBalance().getId(), _login_user_id, reqOrderDetail.getBalanceAmount())) {
							throw new PlatformException(ErrorEnum.C20125, ErrorEnum.C20125.getMessage());
						}
					} else {//扣除可用，增加冻结
						if (!userMoneyService.updateFreezeAmount(_log_user_money.getBalance().getId(), _login_user_id, reqOrderDetail.getBalanceAmount())) {
							throw new PlatformException(ErrorEnum.C20125, ErrorEnum.C20125.getMessage());
						}
					}

					MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(5);
					if (moneyBusinessType != null) {
						//记录事务
						Commision commision = new Commision();
						commision.setOrderDetailId(0l);
						commision.setCreateTime(_now_time);
						commision.setUpdateTime(_now_time);
						commision.setOrderInfoId(0l);
						commision.setOrderObjectId(addOrderObj.getId());
						commision.setUserId(_login_user_id);
						commision.setType(_login_user.getLevel());
						commision.setComment(moneyBusinessType.getTypeName());
						commision.setFee(-addOrderObj.getBalancePaid());
						commision.setSourceId(addOrderObj.getId());//源ID
						commision.setIsCustom(0);//是否手工
						if (respAddOrderInfo.isPaid()) {
							commision.setResult(1);//已处理
							commision.setStatus(1);//可用
							commision.setResultTime(_now_time);
						} else {
							commision.setResult(0);//未处理
							commision.setStatus(0);//禁用
						}
						commision.setBusinessTypeId(moneyBusinessType.getTypeId());//类型id
						commision.setBusinessTypeName(moneyBusinessType.getTypeName());//类型名字
						//保存
						commisionMapper.insertSelective(commision);
						// 记录用户资产的变化
						CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
						_add_user_money_change_list.add(addCUserMoneyChange);

						addCUserMoneyChange.setChangeTime(nowTime.toDate());
						addCUserMoneyChange.setCreatorId(_login_user_id);
						addCUserMoneyChange.setUserId(_login_user_id);
						addCUserMoneyChange.setOrderSn(addOrderObj.getId());// 源ID
						addCUserMoneyChange.setExtend1(addOrderObj.getOrderSn());
						addCUserMoneyChange.setChangeAmount(commision.getFee());
						addCUserMoneyChange.setNormalBeforAmount(_log_user_money.getBalance().getNormalAmount());
						addCUserMoneyChange.setFreeBeforAmount(_log_user_money.getBalance().getFrozenAmount());
						addCUserMoneyChange.setSourceType(Byte.valueOf("1"));// 余额

						if (respAddOrderInfo.isPaid()) {//已支付
							addCUserMoneyChange.setChangeFreeAmount(0);
							//插入流水
							UserJournal balanceJournal = new UserJournal();
							balanceJournal.setCreateTime(_now_time);
							balanceJournal.setUpdateTime(_now_time);
							balanceJournal.setUserId(_login_user_id);
							balanceJournal.setCommisionId(commision.getId());
							balanceJournal.setOrderSn(addOrderObj.getOrderSn());
							balanceJournal.setPromotionDetailId(addOrderObj.getPromotionId());
							balanceJournal.setMoney(addOrderObj.getBalancePaid());
							balanceJournal.setComment(moneyBusinessType.getTypeName());
							balanceJournal.setStatus(UserJournalStatusEnum.S7.getCode());
							balanceJournal.setType(CommonConstants.USER_JOURNAL_TYPE_SUB);
							balanceJournal.setBusinessTypeId(moneyBusinessType.getTypeId());
							balanceJournal.setBusinessTypeName(moneyBusinessType.getTypeName());
							balanceJournal.setIsDelete(0);
							balanceJournal.setKeepAccountsType(moneyBusinessType.getKeepAccountsType());
							userJournalService.insertSelective(balanceJournal);
						} else {//未支付
							addCUserMoneyChange.setChangeFreeAmount(addOrderObj.getBalancePaid());
						}
					}
				}
				//记录变化日志
				saveUserMoneyChange(_login_user_id, _add_user_money_change_list);
			}

			//计算分佣
			addCommision(_login_user, addOrderObj, _check_inventory_map, orderInfoIdMap);

			if (respAddOrderInfo.isPaid()) {
				//支付成功发送短信
				sendSuccessOrderPaymentSms(orderSn, _login_user.getUserName(), addOrderObj.getTotalFee());
				//发送兔币
				sendRedPacketByPayment(orderSn, isOpenStoreOrder, _login_user, addOrderObj.getOpenStoreUserId());
			} else {
				respAddOrderInfo.getPayTypeConfigList().addAll(getPayType(isOpenStoreOrder, reqOrderDetail.getReqHeader(), _login_user));
			}
			respAddOrderInfo.setOpenStoreOrder(isOpenStoreOrder);
			respAddOrderInfo.setPayable(true);
			respAddOrderInfo.setClearCart(true);
			respAddOrderInfo.setpId(addOrderObj.getId());
			_avl_goods_list.clear();
			orderActivInfoVo = null;
			respAddOrderInfo.getErrorMsg().clear();
			return resultModel;
		} finally {
			if (resultModel.getCode() != ErrorEnum.C10000.getCode()) {
				respAddOrderInfo.setPayable(false);
				respAddOrderInfo.setRedPacket(reqRedPacket);
				//				respAddOrderInfo.getUserPromotionList().clear();
				if (CollectionUtils.isNotEmpty(selcetAvlProm)) {
					respAddOrderInfo.getUserPromotionList().addAll(selcetAvlProm);
				}
				respAddOrderInfo.setPromotion(respPromotionVo);

				respAddOrderInfo.setToken(UUID.randomUUID().toString());
				_set_order_token(respAddOrderInfo.getToken());
			}
		}
	}

	protected void createOrderObj(OrderObject orderObject, RequestOrderDetail reqOrderDetail, UserAddress userAddress) {
		orderObject.setCashCoin(reqOrderDetail.getCashCoin());
		orderObject.setBalancePaid(reqOrderDetail.getBalanceAmount());
		orderObject.setPromotionId(reqOrderDetail.getPromotionId());
		orderObject.setPayType(reqOrderDetail.getPayType());
		orderObject.setMemberDeliveryAddressId(reqOrderDetail.getMemberDeliveryAddressId());
		orderObject.setDeliveryWay(reqOrderDetail.getDeliveryWay());
		orderObject.setIsBill(reqOrderDetail.getIsBill());
		orderObject.setBillType(reqOrderDetail.getBillType());
		orderObject.setBillHeader(reqOrderDetail.getBillHeader());
		orderObject.setTaxpayerNo(reqOrderDetail.getBillTaxpayerNo());
		orderObject.setLinkMan(userAddress.getLinkMan());
		orderObject.setMobile(userAddress.getMobile());
		orderObject.setProvince(userAddress.getProvince());
		orderObject.setCity(userAddress.getCity());
		orderObject.setArea(userAddress.getArea());
		orderObject.setStreet(userAddress.getStreet());
		orderObject.setAddress(userAddress.getAddress());
		// orderObject.setLon(lon);
		// orderObject.setLat(lat);
		orderObject.setRemark(reqOrderDetail.getRemark());
		orderObject.setPayClientSource(reqOrderDetail.getReqHeader().getPhoneType());
	}

	private void createOrderInfo(OrderInfo orderInfo, RequestOrderDetail requestOrderDetail, StoreVo storeVo, UserAddress userAddress) {
		orderInfo.setOrderSn(OrderUtil.getOrderSn());
		orderInfo.setStoreId(storeVo.getStoreId());
		orderInfo.setStoreName(storeVo.getStoreName());
		orderInfo.setStoreProvince(storeVo.getProvince());
		orderInfo.setStoreCity(storeVo.getCity());
		orderInfo.setStoreArea(storeVo.getArea());
		orderInfo.setStoreAddress(storeVo.getAddress());
		orderInfo.setStoreLon(Double.valueOf(storeVo.getLon() != null ? storeVo.getLon() : "0.000000"));
		orderInfo.setStoreLat(Double.valueOf(storeVo.getLat() != null ? storeVo.getLat() : "0.000000"));
		orderInfo.setSettlementMan(storeVo.getSettlementMan());
		orderInfo.setSettlementAccount(storeVo.getSettlementAccount());
		orderInfo.setSettlementBank(storeVo.getSettlementBank());
		orderInfo.setPayType(requestOrderDetail.getPayType());
		orderInfo.setMemberDeliveryAddressId(requestOrderDetail.getMemberDeliveryAddressId());
		orderInfo.setDeliveryWay(requestOrderDetail.getDeliveryWay());
		orderInfo.setIsBill(requestOrderDetail.getIsBill());
		orderInfo.setBillType(requestOrderDetail.getBillType());
		orderInfo.setBillHeader(requestOrderDetail.getBillHeader());
		orderInfo.setTaxpayerNo(requestOrderDetail.getBillTaxpayerNo());
		orderInfo.setLinkMan(userAddress.getLinkMan());
		orderInfo.setMobile(userAddress.getMobile());
		orderInfo.setProvince(userAddress.getProvince());
		orderInfo.setCity(userAddress.getCity());
		orderInfo.setArea(userAddress.getArea());
		orderInfo.setStreet(userAddress.getStreet());
		orderInfo.setAddress(userAddress.getAddress());
		// orderInfo.setLon(lon);
		// orderInfo.setLat(lat);
		orderInfo.setRemark(requestOrderDetail.getRemark());
		orderInfo.setPointFee(0);
		orderInfo.setRedPacketFee(0l);
		orderInfo.setCommisionFee(0);
		orderInfo.setCashCoin(0);
		orderInfo.setBalancePaid(0);
		orderInfo.setPromotionDiscount(0);
		orderInfo.setoActivDiscountFee(0l);
	}

	/** 校验提交订单请求是否有效 */

	/** 默认运费 */
	private int _get_default_freight() {
		return NumberUtils.toInt(Config.getString("orderFreight"), 0);
	}

	@Override
	protected void setOpenStoreUser(RequestOrderDetail requestOrderDetail, ResponseUser user, OrderObject orderObject) {
		//购买商品为B区&&(用户推荐人身份id不为空||购买商品达人id不为空)
		if (requestOrderDetail.getOrderDetailList().get(0).getGoodsType() == GoodsTypeEnum.T1.getCode() && (user.getRecommendFrom() != null && !user.getRecommendFrom().isEmpty() || requestOrderDetail.getOrderDetailList().get(0).getTalentId().longValue() > 0)) {
			//以购买商品分享达人id为主，如果没有取当前用户推荐人
			if (requestOrderDetail.getOrderDetailList().get(0).getTalentId().longValue() == 0) {
				UserInfo userInfo = userService.selectUserInfoByPersionId(user.getRecommendFrom());
				if (userInfo != null) {
					orderObject.setOpenStoreUserId(userInfo.getUserId());
				}
			} else {
				orderObject.setOpenStoreUserId(requestOrderDetail.getOrderDetailList().get(0).getTalentId());
			}
		}
	}

	@Override
	protected void compOpenStoreDetailPrice(int experience, OrderObject orderObject, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap) {
		//FIXME 是开店单且商品为自营商品(与去交易单时判断不一致，缺少判断商品是否属于b区，目前b、c区不能同时支付，不会出现C区自营商品进行开店首单优惠情况)
		if (orderObject.getOpenStore() != null && orderObject.getOpenStore().intValue() == 1 && inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode()) {
			inventoryMap.get(orderDetail.getInventoryId()).setSalePrice(inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * experience / 100);
		}
	}

	/** 返回开店优惠折扣，如果满足开店订单，标记订单为开店订单 */
	@Override
	protected int compOpenStorePrice(Map<String, BaseRestrictions> baseRestrictionsMap, int openStoreSelfFee, OrderObject orderObject) {
		int experience = baseRestrictionsMap.get(BaseRestrictionsEnum.T6.getText()).getExperience();
		if (openStoreSelfFee >= baseRestrictionsMap.get(BaseRestrictionsEnum.T6.getText()).getRestrictions()) {
			// orderObject.setTotalPrice(orderObject.getTotalPrice()-openStoreSelfFee+openStoreSelfFee*
			// baseRestrictionsMap.get(BaseRestrictionsEnum.T6.getText()).getExperience()/100);
			orderObject.setOpenStore(1);
		}
		return experience;
	}

	@Override
	protected OrderSettlement createOrderSettlement(Map<Long, OrderInfo> orderInfoIdMap, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap, CompanyXz companyXz, boolean isSub, int currSettlementPriceDealer, int currCashCoinDealer, int currBalancePaidDealer) {
		OrderSettlement orderSettlement = createOrderSettlement(orderInfoIdMap, orderDetail, inventoryMap);
		orderSettlement.setGoodsType(orderDetail.getGoodsType());
		orderSettlement.setSelfSupport(inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport());

		orderSettlement.setSettlementRateDealer(inventoryMap.get(orderDetail.getInventoryId()).getSettlementRateDealer());
		orderSettlement.setSettlementRateManager(inventoryMap.get(orderDetail.getInventoryId()).getSettlementRateManager());

		orderSettlement.setSettlementPriceDealer((int) (Math.round((double) orderDetail.getTotalFee() * orderSettlement.getSettlementRateDealer() / 100)));
		orderSettlement.setCashCoinDealer((int) (Math.round((double) orderDetail.getCashCoin() * orderSettlement.getSettlementRateDealer() / 100)));
		orderSettlement.setBalancePaidDealer((int) (Math.round((double) orderDetail.getBalancePaid() * orderSettlement.getSettlementRateDealer() / 100)));

		orderSettlement.setSettlementPriceManager(orderDetail.getTotalFee() - orderSettlement.getSettlementPriceDealer());
		orderSettlement.setCashCoinManager(orderDetail.getCashCoin() - orderSettlement.getCashCoinDealer());
		orderSettlement.setBalancePaidManager(orderDetail.getBalancePaid() - orderSettlement.getBalancePaidDealer());
		return orderSettlement;
	}

	@Override
	protected int compOIPomotionDiscount(UserPromotion userPromotion, OrderObject orderObject, OrderInfo orderInfo, Map<String, Integer> oinfoBGSalePriceMap, Map<Integer, Integer> bgSalePriceMap) throws PlatformException {
		int promotionDiscount = 0;
		if (userPromotion == null) {//优惠券不存在，默认优惠抵扣为0
			return promotionDiscount;
		}
		switch (userPromotion.getType()) {
			case 1://现金币
						//				promotionDiscount = orderInfo.getTotalPrice().intValue() / orderObject.getTotalPrice() * orderObject.getPromotionDiscount();
					//				break;
			case 2://通用券
			case 7://自主券
				promotionDiscount = (int) (orderInfo.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * orderObject.getPromotionDiscount());
				break;
			case 3://品牌券
				if (!oinfoBGSalePriceMap.containsKey(orderInfo.getStoreId() + "_" + userPromotion.getBrandId())) {
					orderInfo.setPromotionId(0);
					promotionDiscount = -1;
				} else {
					promotionDiscount = (int) (MapUtils.getDoubleValue(oinfoBGSalePriceMap, orderInfo.getStoreId() + "_" + userPromotion.getBrandId(), 0d) / bgSalePriceMap.get(userPromotion.getBrandId()) * orderObject.getPromotionDiscount());
				}
				break;
			case 5://商品券
				if (!oinfoBGSalePriceMap.containsKey(orderInfo.getStoreId() + "_" + userPromotion.getGoodId())) {
					orderInfo.setPromotionId(0);
					promotionDiscount = -1;
				} else {
					promotionDiscount = (int) (MapUtils.getDoubleValue(oinfoBGSalePriceMap, orderInfo.getStoreId() + "_" + userPromotion.getGoodId(), 0d) / bgSalePriceMap.get(userPromotion.getGoodId()) * orderObject.getPromotionDiscount());
				}
				break;
			default://优惠券不可用
				throw new PlatformException(ErrorEnum.C30110, ErrorEnum.C30110.getDesc());
		}
		return promotionDiscount;
	}

	/** 商品行优惠金额计算 */
	protected long compODPomotionDiscount(UserPromotionVo userPromotion, OrderDetail orderDetail, OrderAddParamsVo orderVo) {
		long promotionDiscount = 0;
		if (userPromotion == null || orderDetail.getIsOpenStoreGoods() == 1) {
			return promotionDiscount;
		}
		switch (userPromotion.getType()) {
			case 1://现金币
			case 2://通用券
			case 7://自主券
				promotionDiscount = Math.round(orderDetail.getTotalPrice().doubleValue() / orderVo.getTotalPricePromotion() * userPromotion.getDiscountAmount());
				break;
			case 3://品牌券
				if (orderDetail.getBrandId().intValue() != userPromotion.getBrandId()) {
					promotionDiscount = 0;
				} else {
					promotionDiscount = Math.round(orderDetail.getTotalPrice().doubleValue() / orderVo.getBrandTotalAmount(userPromotion.getBrandId()) * userPromotion.getDiscountAmount());
				}
				break;
			case 5://商品券
				if (orderDetail.getGoodId().intValue() != userPromotion.getGoodId()) {
					promotionDiscount = 0;
				} else {
					promotionDiscount = Math.round(orderDetail.getTotalPrice().doubleValue() / orderVo.getGoodsTotalAmount(userPromotion.getGoodId()) * userPromotion.getDiscountAmount());
				}
				break;
		}
		return promotionDiscount;
	}

	@Override
	protected OpenStoreTypeEnum checkOpenStoreCommision(ResponseUser user, OrderObject orderObject, Map<String, ResponseUser> shareRecommendUserMap, Map<Long, ResponseUser> talentIdAndUserReMap, long talentId) {
		//首单且（存在普通推荐人身份或会员推荐人身份）
		if ((orderObject.getOpenStore() != null && orderObject.getOpenStore() == 1) && (shareRecommendUserMap.get(user.getRecommendFrom()) != null || talentIdAndUserReMap.get(talentId) != null)) {
			if (talentId == 0) {//不是达人分享
				if (shareRecommendUserMap.get(user.getRecommendFrom()).getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {//当前用户为讲师级别，讲师店
					return OpenStoreTypeEnum.T2;
				} else {//学生店
					return OpenStoreTypeEnum.T2;
				}
			} else {//达人商品
				if (talentIdAndUserReMap.get(talentId).getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {//达人为讲师级别
					return OpenStoreTypeEnum.T2;
				} else {//学生店
					return OpenStoreTypeEnum.T2;
				}
			}
		} else {
			return OpenStoreTypeEnum.T0;
		}
	}

	@Override
	protected int openStoreCommision(OpenStoreTypeEnum openStoreTypeEnum, int commisionPrice, Map<String, BaseRestrictions> baseRestrictionsMap, int fee, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		//商品是自营且店铺类型是学生店，计算分佣比例
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && openStoreTypeEnum.getCode() == OpenStoreTypeEnum.T2.getCode()) {
			fee = commisionPrice * baseRestrictionsMap.get(BaseRestrictionsEnum.T7.getText()).getExperience();
		}
		return fee;
	}

	@Override
	protected String openStoreComment(OpenStoreTypeEnum openStoreTypeEnum, String comment, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		//商品是自营且开店店铺类型值大于0，标记为开店分佣
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && openStoreTypeEnum.getCode() > 0) {
			comment = CommonConstants.COMMISION_DESC_OPEN_STORE;
		}
		return comment;
	}

	@Override
	protected int openStoreCommision2(OpenStoreTypeEnum openStoreTypeEnum, int commisionPrice, Map<String, BaseRestrictions> baseRestrictionsMap, int fee, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		//自主商品且是学生店
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && openStoreTypeEnum.getCode() == OpenStoreTypeEnum.T2.getCode()) {
			fee = commisionPrice * baseRestrictionsMap.get(BaseRestrictionsEnum.T7.getText()).getRestrictions();
		}
		return fee;
	}

	@Override
	protected void getUserPromotionOrderList(List<UserPromotionVo> userPromotionList, List<GoodsSimpleVo> goodsList) {
		int totalPrice = 0;
		Map<String, Integer> gbMap = new HashMap<String, Integer>();
		String goodsPrefix = "goods";
		String brandPrefix = "brand";
		boolean hasSelfGoods = false;
		boolean hasNoSelfGoods = false;
		for (GoodsSimpleVo goodsSimpleVo : goodsList) {
			if (!hasSelfGoods && goodsSimpleVo.getSelfSupport() == GoodsSelfTypeEnum.T0.getCode()) {
				hasSelfGoods = true;
			}
			if (!hasNoSelfGoods && goodsSimpleVo.getSelfSupport() == GoodsSelfTypeEnum.T1.getCode()) {
				hasNoSelfGoods = true;
			}
			String goodsKey = goodsPrefix + goodsSimpleVo.getGoodId();
			String brandKey = brandPrefix + goodsSimpleVo.getBrandId();
			if (gbMap.get(goodsKey) == null) {
				gbMap.put(goodsKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity());
			} else {
				gbMap.put(goodsKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity() + gbMap.get(goodsKey));
			}
			if (gbMap.get(brandKey) == null) {
				gbMap.put(brandKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity());
			} else {
				gbMap.put(brandKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity() + gbMap.get(brandKey));
			}
			totalPrice += goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity();
		}
		//		UserPromotionVo userPromotionTemp = null;
		//		int i = 0;
		List<UserPromotionVo> removeList = new ArrayList<UserPromotionVo>();
		for (UserPromotionVo userPromotion : userPromotionList) {
			switch (userPromotion.getType()) {
				case 1://妆币
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else {
						userPromotion.setDiscountAmount(userPromotion.getAmount());
						//						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				case 2://现金券
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * totalPrice / 100);
						}
						//						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				case 3://品牌券
					if (gbMap.get(brandPrefix + userPromotion.getBrandId()) == null) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getLimited() > gbMap.get(brandPrefix + userPromotion.getBrandId())) {
							removeList.add(userPromotion);
						} else {
							if (userPromotion.getIsDiscount() == 0) {
								userPromotion.setDiscountAmount(userPromotion.getAmount());
							} else {
								userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * gbMap.get(brandPrefix + userPromotion.getBrandId()) / 100);
							}
							//							orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
						}
					}
					break;
				case 5://商品券
					if (gbMap.get(goodsPrefix + userPromotion.getGoodId()) == null) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getLimited() > gbMap.get(goodsPrefix + userPromotion.getGoodId())) {
							removeList.add(userPromotion);
						} else {
							if (userPromotion.getIsDiscount() == 0) {
								userPromotion.setDiscountAmount(userPromotion.getAmount());
							} else {
								userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * gbMap.get(goodsPrefix + userPromotion.getGoodId()) / 100);
							}
							//							orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
						}
					}
					break;
				case 7://自营非自营
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else if (userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T0.getCode() && hasNoSelfGoods || userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T1.getCode() && hasSelfGoods) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * totalPrice / 100);
						}
						//						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				default://其它类型不可用
					removeList.add(userPromotion);
			}
			//			i++;
		}
		Collection<UserPromotionVo> existsAll = CollectionUtils.removeAll(userPromotionList, removeList);
		userPromotionList.clear();
		userPromotionList.addAll(existsAll);
		Collections.sort(userPromotionList, new UserPromotionComparator());
	}

	@Override
	public int updateOrderObjectPayUrlById(long id, String payUrl) {
		return 0;
	}

	@Override
	public String selectDivideString(Long orderDetailId) {
		return null;
	}

	@Override
	public void updateOrderObjectFreightNo(Long orderObjectId, String refundFeeNo) {}

	@Override
	public int selectDetailGoodsType(Long id) {
		return 0;
	}

	@Override
	public String selectSettlementAccount(Long orderObjectId) {
		return null;
	}

	@Override
	public List<String> selectOrderClearing() {
		return null;
	}

	@Override
	public void OrderSettlementartificialEliminate(List<String> orderObjectSn) {}

	@Override
	public List<User> selectOrderRecommendFromUser(Long id) {
		return null;
	}

}